# 工具类代码，所有的应用都可能用到
import random
import json
from django.http import HttpResponse
from datetime import date, datetime, timedelta


EXCEPTION_REQUEST = '请不要请求接口，对本站造成损失将追究法律责任'
EX_NAME = '基于区块链的供应链金融虚拟仿真实验项目'


def generate_code(number):
    source = 'qwertyuioppalksjhdgfmbzvcxnQWERTOIUYLKAJSDHGFDSZMNBXVC12345678998745632100'
    code = ''
    for i in range(number):
        code += random.choice(source)
    return code


def return_json(res):
    """
    返回的是HttpResponse对象，但是内容进行json格式化
    :param res: dictionary object
    :return: HttpResponse Object
    """
    json_res = json.dumps(res)
    response = HttpResponse(json_res)
    return response


def illegal_request():
    return return_json({'code': 1001, 'msg': EXCEPTION_REQUEST})


def isAdmin(request):
    return request.session.get('type') == '管理员'


# 随机产生指定位数的随机数
def generate_num(number):
    source = '0123456789'
    code = ''
    for i in range(number):
        code += random.choice(source)
    return code


# 返回用户登录状态
def get_userstate(request):
    return request.session.get("loginFlag")


class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


def get_last_n_days(n):
    """
    :param n: last n days
    :return: last n days' dates in date object type
    """
    today = datetime.now()
    res = []
    for i in range(1, n+1):
        offset = timedelta(days=-i)
        res.append(datetime.date((today + offset)))
    res.reverse()  # return null, act on the original object
    return res


def get_last_n_days_str(n):
    """
    :param n: last n days
    :return: last n days' dates in str
    """
    today = datetime.now()
    res = []
    for i in range(1, n+1):
        offset = timedelta(days=-i)
        res.append((today + offset).strftime('%Y-%m-%d'))
    res.reverse()
    return res

